#!/usr/bin/env python
# coding:utf-8
# author: Wesley

import base64
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA

# 私钥
priKey = '''-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDvFxQfMrIZ78HxtWDQGXZ+4yV2lU35om03ecql9ueRrfy9Ji1m6p1fCJDjcvgqLsrIlENAtwIhG5qRoxuYGLUTlUXrQKCJxpOpDCe8/i6+jNS58yJPqLiaKudm92oEsTolEJvBX53G1uxpS5nUeRedOrKhpJQ0u8zmr9/YsO4L2QIDAQABAoGAcddWUGiOHwVnHlTTrSKCpnY3b1g2EYgCYujN0epXZqkmb1XPRnKtzgNBIdurSEKRcaIOx7CcBfGjznaQfAI/rRDLDDPmJHgIXgsj0BHJ6ImyUwsFxiZqwHLdar9qa+47I6OjdRoIidSjS+hcJtdrKcsaB2eTSBmbMNXC+KTp5gECQQD4wByOR9QiEVGKmUD5hLWceJNLj2Oq6++sAzB6BJksobGrV2cfKAjRm4L0xsvnIIE7yaJaQqMPgTRJVhyCHCqZAkEA9g7kpoe7FI7knZ99Pm1sJp8BiaXc75MqpHMaErysQ+qDuy9LpR2PgwvvHKJbzSfe/4sVgm1VWe9qsP9XdRjzQQJBAIJArnM+X3E7WlRV7XT6rdJyPMbLHahphQWwYdjywXZicNNEoCXrY7rGUKt10V2EYsd4zL+wtwuuXz+rjKAAubkCQQDxItNNqELc+NRu7HgvD8knaDh3jwaf+peVpf9tUV15CYCjlswJOpkEElP4udxBh8twn/sqYL9+bbUfVH1/Ej6BAkAVr103NRONh7gT9sOhZl1WAtMeGmk7I4ssEnE7vXyYY2bysmokdZJFxGb4Hr2V9tuP5jcpPA4ZFruFd/WsCTEe
-----END RSA PRIVATE KEY-----
'''

# 支付宝公钥
pubKey = '''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGh0oazPS6wbNoDc0TNvqLiQxwm559e7sVVnfrGZUndbz930yH1s4+lfkoBUBQ0jGvYvXX+hSdCQOVRQTl7+GfQ0A3qDs3leSAQijrwyUM2rmTZvOT4yWoUrNK1vvKhKTIpeFs/O+iT/bh8SOcBUvoFLA1A1oqwe9cdCC7aI5lGQIDAQAB-----END PUBLIC KEY-----
'''


def sign(data):
    """
    *RSA签名
    * data待签名数据
    * 签名用商户私钥，必须是没有经过pkcs8转换的私钥
    * 最后的签名，需要用base64编码
    * return Sign签名
    """
    key = RSA.importKey(priKey)
    h = SHA.new(data.encode())
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)


def verify(data, signature):
    """*RSA验签
    * data待签名数据
    * signature需要验签的签名
    * 验签用支付宝公钥
    * return 验签是否通过 bool值
    """
    key = RSA.importKey(pubKey)
    h = SHA.new(data.encode())
    verifier = PKCS1_v1_5.new(key)
    if verifier.verify(h, base64.b64decode(signature)):
        return True
    return False


if __name__ == '__main__':
    raw_data = 'partner="1234567890123456"&seller="12345@qq.com"&out_trade_no="123000"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"'
    sign_data = sign(raw_data)
    print("sign_data: ", sign_data)
    print(verify(raw_data, sign_data))
